package cn.wanho.interceptor;




import cn.wanho.CmsUserThreadLocal.UserThreadLocal;
import cn.wanho.dto.CmsUser;
import cn.wanho.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通过该拦截器来对除了login请求意外的所有请求进行用户token判定
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println();
        String token = request.getHeader("token");
        Claims claims = JWTUtil.parseJWT(token);
        String  username = (String)claims.get("name");
        if(username == null){
            return false;
        }
        CmsUser cmsUser = new CmsUser();
       cmsUser.setUsername(username);
        cmsUser.setId((Integer) claims.get("id"));
        UserThreadLocal.set(cmsUser);
        System.out.println(UserThreadLocal.get());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.set(null);
    }


}
